package xhwl.hmo.mall.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

public class ImgLoaderUtil {
	private static volatile ImgLoaderUtil instance;
	private static ImageLoader loader;
	private ImgLoaderUtil(){
		
	}
	public static ImgLoaderUtil getInstance(){
		if(instance==null){
			synchronized (ImageLoader.class) {
				if(instance==null){
					instance=new ImgLoaderUtil();
					loader= ImageLoader.getInstance();
				}
			}
		}
		return instance;
	}
	public void initCachedConfig(Context context) {
		// TODO Auto-generated method stub
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisk(true).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context
				).defaultDisplayImageOptions(defaultOptions)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).build();
		loader.init(config);
	}
	/**
	 * 根据imageView的宽度图片自适应
	 * @param uri
	 * @param imageView
	 */
	public void loadImageAutoResize(String uri,final int width,final ImageView imageView){
		loader.loadImage(uri, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
				// TODO Auto-generated method stub
				int outHeight=(int)(arg2.getHeight()*1.0/arg2.getWidth()*width);
				LayoutParams param = imageView.getLayoutParams();
				param.width=width;
				param.height=outHeight;
				imageView.setLayoutParams(param);
				imageView.setImageBitmap(arg2);
				imageView.setScaleType(ScaleType.FIT_XY);
			}
			
			@Override
			public void onLoadingCancelled(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
		});
	}
}
